<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" style="width: 100%" stripe border>
        <el-table-column type="expand" label="明细" width="width">
          <!-- 展开列 -->
          <template slot-scope="scope">
            <!-- 渲染一级权限 -->
            <el-row :gutter="10" v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="{ bdbottom: true, bdTop: i1 === 0, vCenter: true }">
              <el-col :span="5">
                <el-tag closable type="primary" @close="removeRightsById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row :gutter="10" v-for="(item2, i2) in item1.children" :key="item2.id" :class="{ bdTop: i2 !== 0, vCenter: true }">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightsById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 渲染三级权限 -->
                    <el-col :span="18"
                      ><el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeRightsById(scope.row, item3.id)">{{ item3.authName }}</el-tag></el-col
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="width"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="width"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="width"> </el-table-column>
        <el-table-column label="操作" width="width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" class="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" class="el-icon-delete" @click="removeRoleById(scope.row.id)">删除</el-button>
            <el-button type="warning" size="mini" class="el-icon-setting" @click="showRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
        <el-form ref="addFormRef" :model="addForm" label-width="100px" :rules="addFormRules">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述:" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑角色对话框 -->
      <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
        <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="editFormRules">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述:" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoles">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" width="50%" @close="RightsDialogClosed">
        <el-tree ref="treeRef" show-checkbox :data="rightsList" :props="treeProps" node-key="id" default-expand-all :default-checked-keys='defaultsKeys'> </el-tree>
        <div slot="footer">
          <el-button @click="rightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      addDialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      addFormRules: {
        roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        roleDesc: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
      },
      //编辑
      editDialogVisible: false,
      editForm: {
        roleName: "",
        roleDesc: "",
      },
      editFormRules: {
        roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        roleDesc: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
      },
      userinfo: {},
      //   隐藏分配权限对话框
      rightsDialogVisible: false,
      rightsList:[],
      treeProps:{
          label:'authName',
          children:'children'
      },
    //   默认选中的id数组
      defaultsKeys:[],
      roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  computed: {},
  methods: {
    //获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }

      this.$message.success("获取角色列表成功");
      this.rolesList = res.data;
    },
    //添加角色
    async addRoles() {
      const { data: res } = await this.$http.post("roles", this.addForm);
      if (res.meta.status !== 201) {
        return this.$message.error("添加角色失败");
      }
      this.$message.success("添加角色成功");
      this.getRolesList();
      this.addDialogVisible = false;
    },
    // 显示角色对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.editDialogVisible = true;
      this.$message.success("获取成功");
      this.editForm = res.data;
    },
    //编辑角色
    async editRoles() {
      // this.userinfo=userinfo
      console.log(this.editForm);
      const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc });
      if (res.meta.status !== 200) {
        return this.$message.error("修改角色失败");
      }
      this.$message.success("修改角色成功");
      this.getRolesList();
      this.editDialogVisible = false;
    },
    //删除
    removeRoleById(id) {
      this.$confirm("确定要删除该角色吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error("删除角色失败");
          }
          this.$message.success("删除角色成功");
          this.getRolesList();
        })
        .catch(() => {});
    },
    // 删除权限
    removeRightsById(role, rightsId) {
      this.$confirm("确定要删除该权限吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`);
          if (res.meta.status !== 200) {
            return this.$message.error("删除权限失败");
          }
          this.$message.success("删除权限成功");
          // this.getRolesList()
          role.children = res.data; //重新设置当前角色下最新权限数据
          console.log(res.data);
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 显示分配权限对话框
    async showRightsDialog(role) {
        const {data:res}=await this.$http.get(`rights/tree`)
        if(res.meta.status!==200){
            return this.$message.error('获取权限列表失败')
        }
        this.rightsList=res.data
        // 选中所有三级权限id
        this.getRightsId(role)
        this.roleId=role.id

      this.rightsDialogVisible = true;
    },
    // 选中所有三级权限id
    getRightsId(node){
        // 判断是否是三级权限
        if(!node.children){
            return this.defaultsKeys.push(node.id)
        }
        // 如果不是三级权限，则递归操作
        node.children.forEach(item => {
            this.getRightsId(item)
        });
        

    },
    // 监听分配权限对话框关闭
    RightsDialogClosed(){
        this.defaultsKeys=[]
    },

    // 分配权限
    async allotRights(){
        const keys=this.$refs.treeRef.getCheckedKeys().concat(this.$refs.treeRef.getHalfCheckedKeys())
        const idStr=keys.join(',')
        const{data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status!==200){
            return this.$message.error('分配权限失败')
        }
        this.$message.success('分配权限成功')
        this.rightsDialogVisible = false;
        this.getRolesList()
    },
  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 6px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdTop {
  border-top: 1px solid #eee;
}
.vCenter {
  display: flex;
  align-items: center;
}
</style>
